<script setup>
import { ref } from 'vue'
import { updateCurrentUserPasswordService } from '@/api/common.js'

const showPasswordUpdatePopup = ref(false)
const form = ref({
  newPassword: '',
  confirmPassword: ''
})

// 向外暴露方法
const open = () => {
  showPasswordUpdatePopup.value = true
  form.value.newPassword = ''
  form.value.confirmPassword = ''
}

// 密码正则校验
const pattern = /^\w{4,32}$/

// 提交处理
const handleSubmit = async () => {
  if (!form.value.newPassword || !form.value.confirmPassword) {
    showNotify({
      type: 'warning',
      message: '密码不能为空'
    })
    return
  }
  if (form.value.newPassword !== form.value.confirmPassword) {
    showNotify({
      type: 'warning',
      message: '两次密码输入不一致'
    })
    return
  }
  await updateCurrentUserPasswordService(form.value.newPassword)
  showNotify({
    type: 'success',
    message: '密码修改成功'
  })
  showPasswordUpdatePopup.value = false
}

defineExpose({
  open
})
</script>

<template>
  <van-popup
    v-model:show="showPasswordUpdatePopup"
    destroy-on-close
    round
    position="bottom"
    :style="{ height: '38%' }"
  >
    <div class="password-update">
      <div class="title">修改密码</div>
      <van-form class="form-container" @submit="handleSubmit">
        <van-field
          v-model="form.newPassword"
          name="newPassword"
          label="新密码"
          placeholder="请输入新密码"
          type="password"
          :rules="[{ pattern, message: '密码必须是4~32位的字母,数字,下划线' }]"
        />
        <van-field
          v-model="form.confirmPassword"
          name="confirmPassword"
          label="确认密码"
          placeholder="请再次输入新密码"
          type="password"
          :rules="[{ pattern, message: '密码必须是4~32位的字母,数字,下划线' }]"
        />
        <div class="button-group">
          <van-button round block type="primary" native-type="submit">确认修改</van-button>
        </div>
      </van-form>
    </div>
  </van-popup>
</template>

<style lang="scss" scoped>
.password-update {
  background-color: #f7f8fa;
  height: 100%;

  .title {
    font-size: 16px;
    font-weight: 600;
    text-align: center;
    padding: 20px 0;
  }

  .form-container {
    padding: 0 16px;

    .van-field {
      margin-bottom: 12px;
      background: white;
      border-radius: 8px;
      padding: 12px 16px;
    }

    .button-group {
      margin-top: 24px;
    }
  }
}
</style>
